<?php

class Project extends CActiveRecord
{
	/**
	 * The followings are the available columns in table 'project':
	 * @var integer $id
	 * @var string $activity
	 * @var string $description
	 * @var string $route_mnemonic
	 * @var integer $owner_id
	 * @var bool $simulation
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'project';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('activity','length','max'=>255),
			array('simulation', 'boolean'),
			array('activity, route_mnemonic', 'required'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'meetings' => array(self::HAS_MANY, 'Meetings', 'project_id', 'order' => 'meeting_date desc'),
			'owner' => array(self::BELONGS_TO, 'Owner', 'owner_id'),
			'route' => array(self::BELONGS_TO, 'Route', 'route_mnemonic'),
			'topics' => array(self::HAS_MANY, 'ProjectTopic', 'project_id', 'order' => 'idx', 'condition' => 'step_id is not null'),
			'allTopics' => array(self::HAS_MANY, 'ProjectTopic', 'project_id', 'order' => 'idx'),
		);
	}

	public function getTitle()
	{
		return "#" . $this->id . " " . $this->owner->first_name . " " . $this->owner->last_name . " - " . $this->activity;
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => Yii::t('database', 'Id'),
			'activity' => Yii::t('database', 'Activity'),
			'description' => Yii::t('database', 'Description'),
			'route_mnemonic' => Yii::t('database', 'Route'),
			'owner_id' => Yii::t('database', 'Owner'),
			'simulation' => Yii::t('database', 'Simulation'),
		);
	}
	
	public function getLastMeeting() {
		$meeting = null;
		$meetings = $this->meetings;
		foreach($meetings as $tmp) {
			if ($meeting == null) {
				$meeting = $tmp;
			} else if ($meeting->meeting_date < $tmp->meeting_date) {
				$meeting = $tmp;
			}
		}
		return $meeting;
	}
	
	public function getFirstMeeting() {
		$meeting = null;
		$meetings = $this->meetings;
		foreach($meetings as $tmp) {
			if ($meeting == null) {
				$meeting = $tmp;
			} else if ($meeting->meeting_date > $tmp->meeting_date) {
				$meeting = $tmp;
			}
		}
		return $meeting;
	}
	
	public function __toString() {
		return $this->owner->fullName . " - " . $this->activity . " - " . $this->owner->city->label;
	}
	
	public function getNbDays() {
		$meeting_date = new Date(strtotime($this->getFirstMeeting()->meeting_date));
		return DateUtils::daysDiff(new Date(), $meeting_date);
	}
}